package com.bbs.service.impl;

import com.bbs.dao.UserDao;
import com.bbs.entity.User;
import com.bbs.service.UserService;
import com.bbs.utils.MailUtils;
import com.bbs.utils.MyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import java.util.Random;

@Component("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public User findById(int id) {
        User user = userDao.findById(id);
        return user;
    }

    @Override
    public List<User> listUserByHot() {
        List<User> user = userDao.listUserByHot();
        return user;
    }

    @Override
    public List<User> listUserByTime() {
        List<User> user = userDao.listUserByTime();
        return user;
    }
    @Override
    public int register(User user){
        //判断邮箱是否被占用，占用就返回2给LoginController
        if (Objects.nonNull(userDao.findByEmail(user.getEmail()))){
            return 2;
        }
        //构造user,设置未激活
        user.setActived(0);
        String activateCod = MyUtil.createActivateCode();
        user.setActivateCode(activateCod);//随机不能重复的激活码
        user.setJoinTime(MyUtil.formatDate(new Date()));//注册时间
        user.setUsername("JM"+new Random().nextInt(10000)+"号");//用户名，JM+随机
        user.setHeadUrl("http://static.yidianzixun.com/beauty/imgs/i_000cfwku.jpg");//用户头像地址
        int flag = userDao.insertUser(user);
        if (flag == 1){
            //发送邮件
            //getActivateCode()唯一注册激活
            String content = "<a href='http://localhost:8080/ssm_bbs_war_exploded/tse?code="+user.getActivateCode()+"'>点击激活【野鸡大学】</a> ";
            MailUtils.sendMail(user.getEmail(),content,"激活账号");
        }
        return flag;
    }

    @Override
    public int update(String code) {
        userDao.update(code);
        return 0;
    }

    @Override
    public User checkPassword(User user){
        User myUser = userDao.checkPassword(user);
        return myUser;
    }

    @Override
    public void updateUser(User user) {
            userDao.updateUser(user);
//        return updateUser;
    }
//个人获赞数量
    @Override
    public void updatelikeCount(int uid) {
        userDao.updatelikeCount(uid);
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.invalidate();
        return "login";
    }
}
